package com.example.warehouseplus.service.impl;

import com.example.warehouseplus.dao.ItemRepository;
import com.example.warehouseplus.entity.Item;
import com.example.warehouseplus.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemRepository itemRepository;
    @Override
    public Flux<Item> getAllItems() {
        return itemRepository.findAll();
    }

    @Override
    public Mono<Item> getItemByName(String name) {
        return itemRepository.findByName(name);
    }

    @Override
    public Mono<Item> createItem(Item item) {
        return itemRepository.save(item);
    }

    @Override
    public Mono<Item> updateItem(String name, Item item) {
        return itemRepository.findByName(name)
                .flatMap(existingItem -> {
                    existingItem.setName(name);
                    existingItem.setPrice(item.getPrice());
                    existingItem.setQuantity(item.getQuantity());
                    return itemRepository.save(existingItem);
                });
    }

    @Override
    public Mono<Void> deleteItem(String name) {
        return itemRepository.deleteByName(name);
    }

    @Override
    public Flux<Item> uploadItems(List<Item> items) {
        return itemRepository.saveAll(items);
    }

    @Override
    public Flux<Item> getItemsByPriceRange(double minPrice, double maxPrice) {
        return itemRepository.findByPriceBetween(minPrice, maxPrice);
    }
}
